<template>
  <a-card :bordered="false" :style="{ height: '100%' }">
    <div>
      <a-form :form="form">
        <a-form-item
          label="角色名称"
          :label-col="{lg: {span: 7}, sm: {span: 7}}"
          :wrapper-col="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            v-decorator="[ 'name', {rules: [{ required: true, message: '请输入角色名称' }]} ]"
            placeholder="请填写角色名称"
          />
        </a-form-item>

        <a-form-item
          label="拥有权限"
          :label-col="{lg: {span: 7}, sm: {span: 7}}"
          :wrapper-col="{lg: {span: 12}, sm: {span: 17} }"
        >
          <br />
          <a-row
            :gutter="16"
            v-for="(permission, index) in nav"
            :key="index"
            :style="{marginBottom:'36px'}"
          >
            <a-col :span="19" style="margin: 10px 0 24px 0">
              <a-checkbox
                v-if="permission.nav.length > 0"
                :indeterminate="permission.indeterminate"
                :checked="permission.checkedAll"
                @change="onChangeCheckAll($event, permission)"
              >{{ permission.title }}</a-checkbox>
              <a-divider style="margin: 0 0 8px 0" />
              <div
                v-for="(permissionitem, i) in permission.nav"
                :key="i"
                style="margin: 0 0 0 24px"
              >
                <a-checkbox
                  :checked="permissionitem.checked"
                  @change="onChangeCheckItem($event, permission, permissionitem)"
                >{{ permissionitem.title }}</a-checkbox>
                <a-checkbox
                  style="margin: 0 0 0 24px"
                  v-if="permissionitem.actionsOptions"
                  :indeterminate="permissionitem.indeterminate"
                  :checked="permissionitem.checkedAll"
                  @change="onChangeCheckItemAll($event, permission, permissionitem)"
                >全选</a-checkbox>
                <a-checkbox-group
                  style="margin: 0 0 0 6px"
                  v-if="permissionitem.actionsOptions"
                  :options="permissionitem.actionsOptions"
                  v-model="permissionitem.selected"
                  @change="onChangeCheck(permission, permissionitem)"
                />
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 24 }" style="text-align: center">
          <a-button type="primary" @click="save">保存</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'

export default {
  components: {},
  data() {
    return {
      form: this.$form.createForm(this),
      id: '',
      nav: [],
      navs: [],
      auths: [],
      info: {},
    }
  },
  created() {},
  activated() {
    this.getnavs()
  },
  methods: {
    init() {
      this.navs = []
      this.auths = []
      this.info = {}
      this.id = ''
      this.form.resetFields()
    },
    get() {
      this.$get('/api/user/user_role_get', { id: this.id }).then((res) => {
        this.info = res || {}
        if (res) {
          setTimeout(
            this.form.setFieldsValue({
              name: res.name,
            })
          )
          var qx = res.navs ? res.navs.split(',') : []
          if (qx && this.nav) {
            this.nav.forEach((permission) => {
              permission.nav.forEach((item) => {
                if (qx.find((qxr) => qxr * 1 === item.id)) {
                  item.checked = true
                }
                if (item.actionsOptions) {
                  var px = res.auths ? res.auths.split(',') : []
                  item.actionsOptions.forEach((ao) => {
                    var sid = px.find((pxr) => pxr * 1 === ao.value)
                    if (sid) {
                      item.selected.push(sid * 1)
                    }
                  })
                  item.indeterminate = !!item.selected.length && item.selected.length < item.actionsOptions.length
                  item.checkedAll = item.selected.length === item.actionsOptions.length
                }
              })
              this.computepermission(permission)
            })
          }
        }
      })
    },
    getnavs() {
      this.$get('/api/user/user_nav_gets').then((res) => {
        if (res) {
          if (res[0].nav) {
            res[0].nav.forEach((navs) => {
              navs.checkedAll = false
              navs.indeterminate = false
              navs.nav.forEach((item) => {
                item.checkedAll = false
                item.indeterminate = false
                item.checked = false
                item.selected = []
                if (item.user_nav_auth) {
                  item.actionsOptions = item.user_nav_auth.map((option) => {
                    return {
                      label: option.name,
                      value: option.id,
                    }
                  })
                }
              })
            })
            this.nav = res[0].nav
            if (this.$route.params.id) {
              this.id = this.$route.params.id
              this.get()
            } else {
              if (this.id !== '') {
                this.init()
              }
            }
          }
        }
      })
    },
    // 权限选择
    onChangeCheck(permission, permissionitem) {
      permissionitem.indeterminate =
        !!permissionitem.selected.length && permissionitem.selected.length < permissionitem.actionsOptions.length
      permissionitem.checkedAll = permissionitem.selected.length === permissionitem.actionsOptions.length
      if (permissionitem.selected.length) {
        permissionitem.checked = !!permissionitem.selected.length
      }

      this.computepermission(permission)
    },
    onChangeCheckItem(e, permission, permissionitem) {
      Object.assign(permissionitem, {
        checked: e.target.checked,
      })
      if (!e.target.checked) {
        Object.assign(permissionitem, {
          selected: e.target.checked ? permissionitem.actionsOptions.map((obj) => obj.value) : [],
          indeterminate: false,
          checkedAll: e.target.checked,
        })
      }

      this.computepermission(permission)
    },
    onChangeCheckItemAll(e, permission, permissionitem) {
      Object.assign(permissionitem, {
        selected: e.target.checked ? permissionitem.actionsOptions.map((obj) => obj.value) : [],
        indeterminate: false,
        checkedAll: e.target.checked,
      })
      if (e.target.checked) {
        Object.assign(permissionitem, {
          checked: e.target.checked,
        })
      }

      this.computepermission(permission)
    },
    computepermission(permission) {
      var arr = []
      permission.nav.forEach((item) => {
        if (item.actionsOptions) {
          if (item.checked && item.checkedAll) {
            arr.push(3)
          } else if (!item.checked && !item.checkedAll) {
            arr.push(1)
          } else {
            arr.push(2)
          }
        } else {
          if (item.checked) {
            arr.push(3)
          } else {
            arr.push(1)
          }
        }
      })
      if (arr.find((item) => item === 2) || (arr.find((item) => item === 1) && arr.find((item) => item === 3))) {
        Object.assign(permission, {
          indeterminate: true,
          checkedAll: false,
        })
      } else if (arr[0] === 1) {
        Object.assign(permission, {
          indeterminate: false,
          checkedAll: false,
        })
      } else {
        Object.assign(permission, {
          indeterminate: false,
          checkedAll: true,
        })
      }
    },
    onChangeCheckAll(e, permission) {
      Object.assign(permission, {
        indeterminate: false,
        checkedAll: e.target.checked,
      })
      permission.nav.forEach((item) => {
        Object.assign(item, {
          indeterminate: false,
          checkedAll: e.target.checked,
          checked: e.target.checked,
        })
        if (item.actionsOptions) {
          Object.assign(item, {
            selected: e.target.checked ? item.actionsOptions.map((obj) => obj.value) : [],
          })
        }
      })
    },
    save() {
      this.form.validateFields((err) => {
        if (!err) {
          let data = this.form.getFieldsValue()
          data = Object.assign(this.info, data)
          var arr = ['0']
          var per = ['0']
          this.nav.forEach((permission) => {
            if (permission.indeterminate || permission.checkedAll) {
              arr.push(permission.id)
            }
            permission.nav.forEach((item) => {
              if (item.indeterminate || item.checkedAll || item.checked) {
                arr.push(item.id)
              }
              per.push.apply(per, item.selected)
            })
          })
          if (arr.length === 1) {
            this.$noti.error({
              message: '请至少选择一个权限',
            })
            return
          }
          data.auths = per.join(',')
          data.navs = arr.join(',')
          this.$post('/api/user/user_role_save', { data: JSON.stringify(data) }).then((res) => {
            if (res.data.status === 1) {
              this.$message.success('保存成功')
              this.$router.go(-1)
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
      })
    },
  },
}
</script>

<style scoped>
</style>
